package cn.tedu.toa.management.sys.controller;


import cn.tedu.toa.management.commons.vo.Result;
import cn.tedu.toa.management.sys.entity.SysUsers;
import cn.tedu.toa.management.sys.service.SysUsersService;
import cn.tedu.toa.management.sys.vo.UserVo;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author huaqian
 * @since 2021-09-09
 */
@RestController
@RequestMapping("/sys-users")
public class SysUsersController {

    @Value("${myconfig.page-size}")
    private Integer pageSize;

    @Autowired
    private SysUsersService usersService;

    @RequestMapping("/findUserList")
    public Result<PageInfo<SysUsers>> findUserList(String username,
                               @RequestParam(defaultValue = "1") Integer pageNum){
        PageInfo<SysUsers> pageInfo=usersService.findUserList(username,pageNum,pageSize);
        return Result.ok(pageInfo);
    }

    @RequestMapping("/saveUser")
    public Result saveUser(SysUsers users,Integer[] roleIds){
        usersService.saveUser(users,roleIds);
        return Result.ok();
    }

    @PostMapping("/modifyUserValid")
    public Result modifyUserValid(Integer userId,Integer valid){
        usersService.modifyUserValidByUserId(userId,valid);
        return Result.ok();
    }



    @GetMapping("/getUserByUserId")
    public Result getUserByUserId(int userId){
        UserVo user=usersService.selectUserByUserId(userId);
        return Result.ok(user);
    }

    @PostMapping("/updateUser")
    public Result updateUser(SysUsers users,Integer[] roleIds){
        usersService.updateUser(users,roleIds);
        return Result.ok();
    }

    @PostMapping("/login")
    public Result login(String userName,String password){
        //将页面提交的用户信息 提交给 shiro框架
        UsernamePasswordToken uptoken=new UsernamePasswordToken(userName, password);
        //获取shiro矿机的subject
        Subject subject= SecurityUtils.getSubject();
        //调用subject的login方法启动认证
        subject.login(uptoken);
        return Result.ok();
    }

    @PostMapping("/pwdEdit")
    public Result editPwd(String password,String newPassword){
        //先确认用户密码是否正确
        usersService.updatePwd(password,newPassword);
        return Result.ok();
    }



}
